<template>
  <div>
    <el-upload :action="url" :data="fileData" :file-list="fileList" :show-file-list="true" :limit="limitNumber" :before-upload="beforeUploadHandle" :on-remove="handleRemove" :on-success="successHandle" :class="{hideAdd:uploadDisabled}">
      <el-button type="primary" v-if="!uploadDisabled">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { ref, withDefaults, defineProps } from "vue";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import app from "@/constants/app";
import { ElMessage } from "element-plus";
import { Failed } from "@element-plus/icons-vue/dist/types";
import type { UploadProps } from "element-plus";

const emit = defineEmits(["updatList"]);

const url = ref("");
const fileData = ref({
  busType: 0
});
const fileList = ref<IObject[]>([]);
// 允许上传图片的数量
const limitNumber = ref<number>(1);
// 控制是否显示上传按钮
const uploadDisabled = ref<boolean>(false);

const props = withDefaults(
  defineProps<{
    urlList: string[];
    limitImgNumber?: number;
  }>(),
  {
    limitImgNumber: 1 // 默认值
  }
);

const init = () => {
  url.value = `${app.api}/sys/oss/uploadServer?token=${getToken()}`;
  fileList.value = (props.urlList as any[]) || [];
  limitNumber.value = props.limitImgNumber;
  uploadDisabled.value = fileList.value.length >= limitNumber.value;
};

// 上传之前
const beforeUploadHandle = (file: IObject) => {
  uploadDisabled.value = limitNumber.value == 1 && file ? true : false;
};

// 文件上传变化
const handleFileChange = (file: IObject, fileList: IObject[]) => {
  uploadDisabled.value = fileList.length >= limitNumber.value;
};

// 上传成功
const successHandle = (res: IObject, file: IObject, list: IObject[]) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }

  fileList.value = list;
  emit("updatList", list);
};

// 删除
const handleRemove: UploadProps["onRemove"] = (file: IObject, fileList: IObject[]) => {
  fileList.value = [];
  emit("updatList", fileList.value);
  //手动触发change事件
  handleFileChange(file, fileList);
};

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
.hideAdd {
  :deep .el-upload.el-upload--text {
    display: none;
  }

  :deep .el-upload-list.el-upload-list--text {
    margin: 0px;
  }
}

:deep .el-upload-dragger {
  width: 100%;
  height: 180px;
  padding: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-upload__tip {
  text-align: left;
}
</style>